import Vue from "vue";
import axios from "axios";
import router from "@/router";
import qs from "qs";
// 在common.js文件中统一存放一些公共常量，方便之后维护
import "./common.js";
import defaultConfig from "@/config/index";
import { Base64 } from "js-base64";
import store from "@/store.js";

// 添加请求拦截器，在发送请求之前做些什么(**具体查看axios文档**)--------------------------------------------
axios.interceptors.request.use(
  function (config) {
    // 显示loading
    // 在请求发送之前做一些处理
    const token = localStorage.token; // util.cookies.get('token');
    // 让每个请求携带token-- ['Authorization']为自定义key 请根据实际情况自行修改
    config.headers["Authorization"] = `Basic ${Base64.encode(
      `${defaultConfig.clientId}:${defaultConfig.clientSecret}`
    )}`;
    config.headers["qdport-Auth"] = "bearer " + token;
    config.headers["sgkj-Auth"] = "bearer " + token;
    // config.headers['module_name'] = localStorage.getItem('module_name') || '';
    return config;
  },
  function (error) {
    // 请求错误时弹框提示，或做些其他事
    return Promise.reject(error);
  }
);

// 添加响应拦截器(**具体查看axios文档**)----------------------------------------------------------------
axios.interceptors.response.use(
  function (response) {
    // 如果只需要返回体中数据，则如下，如果需要全部，则 return response 即可
    if (response.data && response.data.code == 400) {
      // indexOf()返回值为 - 1表示该字符串没有出现
      if (response.data.message && response.data.message.indexOf("过期") > -1) {
        // 清空token和refreshToken
        localStorage.setItem("token", "");
        localStorage.setItem("refreshToken", "");
        // 返回login页面
        // router.push("/login")
      }
    }
    if (response.code === 401) {
      // var that = this;
      // this.$warning({
      //   title: '登录失效',
      //   content: "您当前未登录，请先登录",
      //   onOk(){
      //     that.$router.push('/login');
      //   }
      // });
      // this.$router.push('/login');
    } else if (response.code == 600) {
      this.$router.push("/apply");
    }
    return response.data;
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

// 封装数据返回失败提示函数---------------------------------------------------------------------------
function errorState(response) {
  // 隐藏loading
  // 如果http状态码正常，则直接返回数据
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    // 如果不需要除了data之外的数据，可以直接 return response.data

    return response;
  } else if (response == "Error: Network Error" && !location.origin.includes(":808")) {
    // 请求错误跳转到，，某一特定页面
    // router.push("/apply");
    // 测试-跳转到主网站
    // location.href = "https://10-167-71-288082-8r197iu0wcn4up.ztna-dingtalk.com/dingreport/";
  } else if (response.request.status == 401) {
    // includes(401)
    localStorage.setItem("redirect_uri", `${location.href}`);
    router.push("/iamSso");
  }
}

// 封装数据返回成功提示函数---------------------------------------------------------------------------
function successState(res) {
  // 隐藏loading
  // 统一判断后端返回的错误码(错误码与后台协商而定)
  if (res.code === 200) {
    return res;
  }
  if (res.code == 401) {
    // || res.code == 400
    localStorage.setItem("token", "");
    localStorage.setItem("refreshToken", "");
    // router.push("/iamSso");
  }
  // 后端返回600 则是系统中查无此人就需要去跳转到申请信息填写的页面下
  if (res.code == 600) {
    router.push("/apply");
  }
}

// 封装axios--------------------------------------------------------------------------------------
function apiAxios(method, url, params, header, config) {
  // let module_name = localStorage.getItem('module_name');
  // if(module_name) {
  //   params.module_name = module_name
  // }

  let httpDefault = {
    method: method,
    // baseURL: Vue.prototype.$baseURL,//调用common.js的baseURL的公共参数
    url: url,
    // `params` 是即将与请求一起发送的 URL 参数
    // `data` 是作为请求主体被发送的数据
    params: method === "GET" || method === "DELETE" ? params : null,
    data: method === "POST" || method === "PUT" ? qs.stringify(params) : null,
    timeout: 6000000,
    header: header,
    // headers: header || { 'Content-Type': 'application/json;charset=UTF-8' },
    ...config,
  };

  if (
    url.includes("role/getfolwdatabydept") ||
    url.includes("screen/get4protlight") ||
    url.includes("role/getfolwdatabyraletime") ||
    url.includes("role/getfolwdatabyhidden") ||
    url.includes("role/getsguser") ||
    url.includes("/role/") ||
    url.includes("/app/") ||
    url.includes("/screen/") ||
    url.includes("/flow/Analyse/") ||
    url.includes("/flow/type/") ||
    url.includes("/form/form") ||
    url.includes("/sdgkscreen/") ||
    url.includes("/form/") ||
    url.includes("/from/") ||
    url.includes("/ding/")
  ) {
    httpDefault["data"] = params;
  }

  if (
    url.includes("10.161.108") ||
    url.includes("http://10.161.") ||
    url.includes("10.161.108.167") ||
    url.includes("10.161.32.89") ||
    url.includes("10.167.87.8")
  ) {
    // 用户唯一码
    // 0222125408612760415 --AI
    httpDefault["headers"] = { ...httpDefault["headers"], "remote-user": "SN160898" };
  }
  let SET_USER_INFO = localStorage.getItem("SET_USER_INFO");
  let SET_USER_TOKEN = localStorage.getItem("SET_USER_TOKEN");
  // 补充iam登录信息
  if (SET_USER_INFO) {
    httpDefault["headers"] = { ...httpDefault["headers"], "remote-user": SET_USER_INFO };
  }
  if (SET_USER_TOKEN) {
    httpDefault["headers"] = { ...httpDefault["headers"], "iam-token": SET_USER_TOKEN };
  }

  // 注意**Promise**使用(Promise首字母大写)
  return new Promise((resolve, reject) => {
    axios(httpDefault)
      // 此处的.then属于axios
      .then((res) => {
        // router.push("/login")
        successState(res);
        resolve(res);
      })
      .catch((response) => {
        // 接口status 为400等后续问题
        let res = JSON.parse(JSON.stringify(response));
        if (res.response && res.response.data && res.response.data.msg) {
          successState(res.response.data);
          resolve(res.response.data);
        } else {
          errorState(response);
          reject(response);
        }
      });
  });
}

// axios body
function apiBodyAxios(url, params, header) {
  // 测试代码-手动补充SN码
  // if (url.includes('big/screen/getuser') && (url.includes('10.161.107.26') || url.includes('localhost'))) {
  //   header = {
  //     ...header,
  //     'remote-user': '0222125408612760415',
  //   }
  // }
  let httpDefault = {
    method: "POST",
    baseURL: Vue.prototype.$baseURL, //调用common.js的baseURL的公共参数
    url: url,
    data: params,
    headers: header || { "Content-Type": "application/json;charset=UTF-8" },
    timeout: 6000000,
  };

  // 注意**Promise**使用(Promise首字母大写)
  return new Promise((resolve, reject) => {
    axios(httpDefault)
      // 此处的.then属于axios
      .then((res) => {
        // router.push("/login")
        successState(res);
        resolve(res);
      })
      .catch((response) => {
        errorState(response);
        reject(response);
      });
  });
}
function putJsonAxios(url, params, header) {
  let httpDefault = {
    method: "put",
    baseURL: Vue.prototype.$baseURL, //调用common.js的baseURL的公共参数
    url: url,
    data: params,
    headers: header || { "Content-Type": "application/json;charset=UTF-8" },
    timeout: 6000000,
  };

  // 注意**Promise**使用(Promise首字母大写)
  return new Promise((resolve, reject) => {
    axios(httpDefault)
      // 此处的.then属于axios
      .then((res) => {
        // router.push("/login")
        successState(res);
        resolve(res);
      })
      .catch((response) => {
        errorState(response);
        reject(response);
      });
  });
}

// axios body
// function apiPostAxios(url, params, data, header) {
//   let httpDefault = {
//     method: 'POST',
//     baseURL: Vue.prototype.$baseURL,//调用common.js的baseURL的公共参数
//     url: url,
//     params,
//     data,
//     headers: header || { 'Content-Type': 'application/json;charset=UTF-8' },
//     timeout: 6000000
//   }

//   // 注意**Promise**使用(Promise首字母大写)
//   return new Promise((resolve, reject) => {
//     axios(httpDefault)
//       // 此处的.then属于axios
//       .then((res) => {
//         // router.push("/login")
//         successState(res)
//         resolve(res)
//       }).catch((response) => {
//         errorState(response)
//         reject(response)
//       })
//   })
// }

// 输出函数getAxios、postAxios、putAxios、delectAxios，供其他文件调用-----------------------------
// Vue.js的插件应当有一个公开方法 install。这个方法的第一个参数是 Vue 构造器，第二个参数是一个可选的选项对象。
export default {
  install: function (Vue) {
    Vue.prototype.getAxios = (url, params, header, config) =>
      apiAxios("GET", url, params, header, config);
    Vue.prototype.postAxios = (url, params, header) => apiAxios("POST", url, params, header);
    Vue.prototype.postBodyAxios = (url, params, header) => apiBodyAxios(url, params, header);
    // Vue.prototype.postGAxios = (url, params, header) => apiPostAxios(url, params, header)
    Vue.prototype.putAxios = (url, params) => apiAxios("PUT", url, params);
    Vue.prototype.putJsonAxios = (url, params, header) => putJsonAxios(url, params, header);
    Vue.prototype.delectAxios = (url, params) => apiAxios("DELECT", url, params);
  },
};
